import axios from 'axios'
import qs from 'qs'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import router from '@/router'
import { getToken, getUserInfo } from '@/utils/auth'
import { getOnceTokenFn } from '@/api/getOnceToken'
// create an axios instance
console.log(process.env.NODE_ENV)
const service = axios.create({
  //110版
  baseURL:window.location.protocol+ '//' + window.location.hostname + ':8088' + process.env.VUE_APP_BASE_API2,
  //正式版 与 开发
  // baseURL: process.env.NODE_ENV === 'development'? (window.location.protocol+ '//' + '172.16.0.57' + ':8088' + process.env.VUE_APP_BASE_API2) : process.env.VUE_APP_BASE_API2, // process.env.VUE_APP_BASE_API2, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 100000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  async config => {
    // do something before request is sent
    // let each request carry token
    // ['X-Token'] is a custom headers key
    // please modify it according to the actual situationteamBlackList
    if (getToken()) {
      config.headers['token'] = getToken()
    }
    if (getToken() && getUserInfo()) {
      const userInfo = JSON.parse(getUserInfo())
      // 请求参数控制
      if ('params' in config) {
        if (typeof config.params === 'undefined') {
          config.params = { 'userId': userInfo.userId }
        } else {
          config.params['userId'] = userInfo.userId
        }
      } else if ('query' in config) {
        config.headers['Content-Type'] = 'application/json'
        config.data = (config.query)
      } else {
        if (typeof config.data === 'undefined') {
          config.data = { 'userId': userInfo.userId }
        } else {
          config.data['userId'] = userInfo.userId
        }
        config.headers['Content-Type'] = 'application/x-www-form-urlencoded'
        config.data = qs.stringify(config.data)
      }
    } else {
      // 请求参数控制
      if (!config.params) {
        if (typeof config.data === 'undefined') {
          config.data = {}
        }
        config.headers['Content-Type'] = 'application/x-www-form-urlencoded'
        if (config.data) {
          config.data = qs.stringify(config.data)
        }
      }
    }

    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const res = response.data
    // if the custom code is not 20000, it is judged as an error.
    if (res.code !== 20000) {
      // 50008: Illegal token 非法token; 50012: Other clients logged in 其他登录; 50014: Token expired 登录过期;
      if (res.code === 50008) {
        // 刷新或重新操作
        Message({
          message: res.message || '非法Token值，请您重新操作或刷新页面',
          type: 'error',
          duration: 5 * 1000
        })
        return new Error('非法Token值，请你重新操作或刷新页面')
      } else if (res.code === 50012 || res.code === 50014) {
        // 重新登录
        MessageBox.confirm('您的登录已过期，您可以取消停留在此页面，或重新登录', {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          store.dispatch('user/logout').then(() => {
            // 跳转逻辑已在permission中处理，此处不作操作
            router.push('/index')
          })
        }).catch(async() => {

        })
      }
      return Promise.reject(new Error(res.message || 'Error'))
      // return new Error(res.message || 'Error')
    } else {
      return res
    }
  },
  error => {
    console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    // return Promise.reject(error)
    return new Error('Error')
  }
)

export default service
